package jp.sinya.register.web.servlet;

import jp.sinya.register.bean.User;
import jp.sinya.register.constants.Constants;
import jp.sinya.register.exception.UserException;
import jp.sinya.register.service.UserService;
import jp.sinya.register.util.CommonUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        UserService userService = new UserService();
        Map<String, String> errorMap = new HashMap<>();
        User user = CommonUtils.toBean(req.getParameterMap(), User.class);

        //用户名校验
        String username = user.getUsername();
        if (username == null || username.trim().isEmpty()) {
            errorMap.put(Constants.USERNAME, "用户名不能为空");
        } else if (username.length() < 3 || username.length() > 15) {
            errorMap.put(Constants.USERNAME, "用户名长度必须在3~15个字符之间");
        }

        //密码校验
        String password = user.getPassword();
        if (password == null || password.trim().isEmpty()) {
            errorMap.put(Constants.PASSWORD, "密码不能为空");
        } else if (password.length() < 6 || password.length() > 15) {
            errorMap.put(Constants.PASSWORD, "密码长度必须在6~15个字符之间");
        }

        //验证码校验
        String verifyCode = (String) req.getSession().getAttribute(Constants.VERIFY_CODE);
        if (verifyCode == null || verifyCode.trim().isEmpty()) {
            errorMap.put(Constants.VERIFY_CODE, "验证码不能为空");
        } else if (verifyCode.length() != 4) {
            errorMap.put(Constants.VERIFY_CODE, "验证码长度必须是4个");
        } else if (!verifyCode.equalsIgnoreCase(user.getVerifyCode())) {
            errorMap.put(Constants.VERIFY_CODE, "验证码错误");
        }

        //注册失败
        if (errorMap.size() > 0) {
            req.setAttribute(Constants.ERROR_MAP, errorMap);
            req.setAttribute(Constants.USER_MSG, user);
            //转发不需要项目名
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
            return;
        }


        //注册成功
        try {
            userService.register(user);
            resp.getWriter().print("<h1>注册成功</h1><br/><a href='" + req.getContextPath() + "/login.jsp" + "'>点击跳转登陆</a>");

        } catch (UserException e) {
            req.setAttribute(Constants.ERROR_MSG, e.getMessage());
            req.setAttribute(Constants.USER_MSG, user);
            //转发不需要带项目名
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
        }
    }
}
